import Vue from 'vue'
import Router from 'vue-router'
import Index from '../components/Index'
import MainContent from '../components/Web/MainContent/Index'
import DetailList from '../components/Web/DetailList/Index'
import DetailContent from '../components/Web/DetailContent/Index'
import NotFound from '../components/Error/404'
import Login from '../components/Login/Index'
import Home from '../components/Home'
import api from '@/http/api'
import store from '@/store'
import Dashboard from '@/components/Manager/Sys/Dashboard'
import { homeUrl, loginUrl, notFound } from '@/utils/global'

Vue.use(Router)

const router = new Router({
    routes: [
        {
            path: homeUrl,
            name: '首页',
            component: Home,
            children: [
                {
                    path: '',
                    name: '仪表盘',
                    component: Dashboard,
                    meta: {
                        icon: 'el-icon-date',
                        index: 0
                    }
                }
            ]
        },
        {
            path: '',
            name: '欢迎页',
            component: Index,
            children: [
                { path: '/', name: '内容区', component: MainContent },
                { path: 'detail/:id', name: '列表', component: DetailList },
                { path: 'detail/:id/:sid', name: '详情', component: DetailContent }
            ]
        },
        // {
        //   path: '/index',
        //   redirect: '/'
        // },
        {
            path: loginUrl,
            name: '登录',
            component: Login
        },
        {
            path: notFound,
            name: '未找到',
            component: NotFound
        },
        {
            path: '*',
            redirect: notFound
        }
    ]
})

function loadIndexData() {
    if (store.state.index.category.length > 0) {
        return
    }
    // 请求首页数据
    api.index.getDatas().then(res => {
    // 加载动态路由
    // let dynamicRoutes = addDynamicRoutes(res.datas)
    // 保存菜单树
        store.commit('setCategory', res.data.category)
        store.commit('setBanner', res.data.banner)
        store.commit('setCarousel', res.data.carousel)
        store.commit('setShareList', res.data.shareList)
        store.commit('setIntro', res.data.intro)
        store.commit('setSuccessList', res.data.successList)
    }).catch(res => {
        console.log('错误：' + res)
    })
}

router.beforeEach((to, from, next) => {
    console.log(to.path)
    if (to.path.endsWith('.ico')) {
        next()
        return
    }
    // 首页加载
    if (to.path === '/') {
        loadIndexData()
        next()
        return
    }
    // 首页详情和404
    if (to.path.startsWith('/detail')) {
        loadIndexData()
        next()
        return
    }

    if (to.path === notFound) {
        next()
        return
    }

    // 登录界面登录成功之后，会把用户信息保存在会话
    // 存在时间为会话生命周期，页面关闭即失效。
    const user = sessionStorage.getItem('user')
    // 如果是访问登录页面，如果用户信息已存在则直接跳转到首页
    if (to.path === loginUrl) {
        if (user) {
            next({ path: homeUrl })
        } else {
            next()
        }
    } else {
        if (!user) {
            // 如果访问非登录页面，且用户信息不存在，则跳转到登录页
            next({ path: loginUrl })
        } else {
            // 加载动态菜单和路由
            addDynamicMenuAndRouters(JSON.parse(user), to, from)
            next()
        }
    }
})

function addDynamicMenuAndRouters(user, to, from) {
    console.log(store.state.app.menuRouteLoaded)
    // 路由已经加载
    if (store.state.app.menuRouteLoaded) {
        return
    }
    // 请求菜单数据
    api.menu.getMenuList({ userId: user.userId }).then(res => {
    // 加载动态路由
        const dynamicRoutes = addDynamicRoutes(res.data)
        // 加入到首页下
        router.options.routes[0].children = router.options.routes[0].children.concat(dynamicRoutes)
        // 添加路由
        router.addRoutes(router.options.routes)
        // 保存加载状态
        store.commit('menuRouteLoaded', true)
        // 保存菜单树
        store.commit('setNavTree', res.data)
    }).catch(res => {
        console.log('错误：' + res)
    })
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addDynamicRoutes(menuList = [], routes = []) {
    let temp = []
    for (let i = 0; i < menuList.length; i++) {
        if (menuList[i].children && menuList[i].children.length >= 1) {
            temp = temp.concat(menuList[i].children)
        } else {
            if (!(menuList[i].permUrl && /\S/.test(menuList[i].permUrl))) {
                continue
            }
            const route = {
                path: menuList[i].permUrl,
                component: null,
                name: menuList[i].description,
                meta: {
                    icon: menuList[i].icon,
                    index: menuList[i].permId
                }
            }
            const arr = menuList[i].permUrl.split('/')
            let url = ''
            for (let i = 0; i < arr.length; i++) {
                if (arr[i] === '') {
                    continue
                }
                url += arr[i].substring(0, 1).toUpperCase() + arr[i].substring(1) + '/'
            }
            url = url.substring(0, url.length - 1)
            route['component'] = resolve => require([`@/components/Manager/${url}`], resolve)
            routes.push(route)
        }
    }
    if (temp.length >= 1) {
        addDynamicRoutes(temp, routes)
    }
    return routes
}

router.afterEach((to, from) => {
    // 路由跳转后，根据参数默认选中菜单页面
    store.commit('setActiveIndex', !to.params.id ? '0' : to.params.id)
})

export default router
